﻿
using Google.Protobuf;
using Llibs.Log;
using UnityEngine;

namespace Client.Hotfix
{
    public static partial class ProtocolHelper
    {
        public enum ELogColor
        {
            None,
            Red,
            Green,
            Blue,
            Cyan,
            Magenta,
            Yellow
        }
        static public GameMessage ToMessage(this byte[] buffer)
        {
            byte[] bytes = Decrypt(buffer);
            return GameMessage.Parser.ParseFrom(bytes);
        }
        
        static public T Parse<T>(this GameMessage message) where T : IMessage, new()
        {
            T m = new T();
            var r = m.Descriptor.Parser.ParseFrom(message.Payload);
            r.Print(ELogColor.Green,"[ws][r]");
            return (T)r;
        }

        static public bool Send(this GameMessage message)
        {
            byte[] b1 = message.ToByteArray();
            byte[] b2 = Encrypt(b1);
            Print(message, "[ws][c]");
            return Api.Instance.Get<NetService>().C2G_WS_Client.Send(b2);
        }

        static public bool Send(this IMessage message,int cmd)
        {
            GameMessage m = new GameMessage { ReqId = cmd, Payload = message.ToByteString()};
            byte[] b1 = m.ToByteArray();
            byte[] b2 = Encrypt(b1);
            Print(message, "[ws][c]");
            return Api.Instance.Get<NetService>().C2G_WS_Client.Send(b2);
        }

        static public void Print(this IMessage message,string pix="[ws][s]")
        {
            Debug.Log($"{pix} : {message}");
        }

        static public void Print(this IMessage message, ELogColor color , string pix = "[ws][s]")
        {
            string m = $"{pix} : {message}";
            Debug.Log(ColorUnityLog(m,color));
        }

        static private string ColorUnityLog(string msg, ELogColor color)
        {
            switch (color)
            {
                case ELogColor.Red:
                    msg = string.Format("<color=#FF0000>{0}</color>", msg);
                    break;
                case ELogColor.Green:
                    msg = string.Format("<color=#00FF00>{0}</color>", msg);
                    break;
                case ELogColor.Blue:
                    msg = string.Format("<color=#0000FF>{0}</color>", msg);
                    break;
                case ELogColor.Cyan:
                    msg = string.Format("<color=#00FFFF>{0}</color>", msg);
                    break;
                case ELogColor.Magenta:
                    msg = string.Format("<color=#FF00FF>{0}</color>", msg);
                    break;
                case ELogColor.Yellow:
                    msg = string.Format("<color=#FFFF00>{0}</color>", msg);
                    break;
                case ELogColor.None:
                default:
                    break;
            }
            return msg;
        }
    }
}